<template>
  <view class="grab-order-detail-page">
    <!-- 顶部导航栏 -->
    <uni-nav-bar 
      :border="false"
      background-color="#ffffff"
      color="#333333"
      title="订单信息"
      left-icon="left"
      @clickLeft="goBack"
    />

    <!-- 订单基本信息 -->
    <view class="order-info-card">
      <view class="info-row">
        <text class="label">订单编号:</text>
        <text class="value">{{ orderDetail.orderNumber }}</text>
      </view>
      <view class="info-row">
        <text class="label">下单时间:</text>
        <text class="value">{{ orderDetail.orderTime }}</text>
      </view>
      <view class="info-row">
        <text class="label">更新时间:</text>
        <text class="value">{{ orderDetail.updateTime }}</text>
      </view>
    </view>

    <!-- 订单详情标题 -->
    <view class="section-title">
      <text>订单详情</text>
    </view>

    <!-- 物品信息详情 -->
    <view class="item-details-card">
      <view class="section-subtitle">
        <text>物品信息详情</text>
      </view>
      
      <view class="item-info">
        <view class="item-row">
          <text class="item-name">{{ orderDetail.itemName }}</text>
          <text class="item-price">{{ orderDetail.price }}元</text>
        </view>
        
        <view class="pickup-location">
          <text class="pickup-label">取货地址:</text>
          <text class="pickup-value">{{ orderDetail.pickupLocation }}</text>
        </view>
      </view>
    </view>

    <!-- 收件人信息 -->
    <view class="recipient-card">
      <view class="recipient-row">
        <text class="recipient-label">收件人:</text>
        <text class="recipient-value">{{ orderDetail.recipientName }}</text>
      </view>
      
      <view class="recipient-row">
        <text class="recipient-label">收件电话:</text>
        <view class="phone-container">
          <text class="phone-icon">📞</text>
          <text class="recipient-value phone">{{ orderDetail.recipientPhone }}</text>
        </view>
      </view>
      
      <view class="recipient-row">
        <text class="recipient-label">收件地址:</text>
        <text class="recipient-value">{{ orderDetail.deliveryAddress }}</text>
      </view>
    </view>

    <!-- 配送详情 -->
    <view class="delivery-details-card">
      <view class="detail-row">
        <text class="detail-label">性别限制:</text>
        <text class="detail-value">{{ orderDetail.genderLimit }}</text>
      </view>
      
      <view class="detail-row">
        <text class="detail-label">送达时间:</text>
        <text class="detail-value">{{ orderDetail.deliveryTime }}</text>
      </view>
      
      <view class="detail-row">
        <text class="detail-label">加价金额:</text>
        <text class="detail-value">{{ orderDetail.extraFee }}</text>
      </view>
      
      <view class="detail-row">
        <text class="detail-label">实际收入:</text>
        <text class="detail-value income">{{ orderDetail.actualIncome }}</text>
      </view>
    </view>

    <!-- 底部操作区 -->
    <view class="bottom-actions">
      <button class="contact-btn" @click="contactCustomer">
        <text class="contact-icon">👥</text>
        <text class="contact-text">联系客服</text>
      </button>
      
      <button class="grab-btn" @click="grabOrder" :disabled="isGrabbing">
        <text v-if="isGrabbing">抢单中...</text>
        <text v-else>抢单</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { requestUrl } from '@/config'

// 声明uni全局变量
declare const uni: any

// 订单详情数据结构
interface GrabOrderDetail {
  id: number
  orderNumber: string
  orderTime: string
  updateTime: string
  itemName: string
  price: string
  pickupLocation: string
  recipientName: string
  recipientPhone: string
  deliveryAddress: string
  genderLimit: string
  deliveryTime: string
  extraFee: string
  actualIncome: string
  serviceType: 'express' | 'takeout'
  originalOrderData?: any
}

// 响应式数据
const orderDetail = ref<GrabOrderDetail>({
  id: 0,
  orderNumber: '2025***************',
  orderTime: '08-18 08:31',
  updateTime: '2025-08-18 08:31:57',
  itemName: '中(鞋盒大小)(零食)校重关',
  price: '3.50',
  pickupLocation: '东院15号楼(二食堂)',
  recipientName: '李',
  recipientPhone: '199****2697',
  deliveryAddress: '***',
  genderLimit: '不限',
  deliveryTime: '08-18 09:01',
  extraFee: '0',
  actualIncome: '3.50',
  serviceType: 'express'
})

const isGrabbing = ref(false)

// 页面加载时获取订单详情
onMounted(() => {
  console.log('抢单详情页面已加载')
  
  // 优先从storage获取传递的订单数据
  const storedOrder = uni.getStorageSync('grabOrderDetail')
  if (storedOrder) {
    console.log('找到storage中的订单数据:', storedOrder)
    const order = JSON.parse(storedOrder)
    loadOrderDetail(order.id)
  } else {
    console.log('未找到storage中的订单数据')
    // 尝试从页面参数获取orderId
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const orderId = currentPage.options?.id
    
    if (orderId) {
      console.log('从页面参数获取到orderId:', orderId)
      loadOrderDetail(Number(orderId))
    } else {
      console.log('未找到任何订单数据')
    }
  }
})

// 获取当前页面实例的方法
const getCurrentPages = (): any[] => {
  return (uni as any).getCurrentPages()
}

// 加载订单详情
const loadOrderDetail = (orderId: number) => {
  console.log('开始加载订单详情，orderId:', orderId)
  
  // 从storage获取传递的订单数据
  const storedOrder = uni.getStorageSync('grabOrderDetail')
  if (storedOrder) {
    const order = JSON.parse(storedOrder)
    console.log('解析后的订单数据:', order)
    
    // 生成更真实的收件人信息
    const recipients = ['张同学', '李同学', '王同学', '赵同学', '刘同学', '陈同学', '杨同学', '黄同学']
    const phones = ['138****8888', '139****9999', '136****6666', '137****7777', '135****5555', '134****4444', '133****3333', '132****2222']
    const randomIndex = order.id % recipients.length
    
    // 根据订单类型和内容生成具体的详情信息
    let itemName = order.title
    let deliveryTime = '30分钟内'
    let pickupLocation = order.pickup
    let deliveryAddress = order.delivery
    
    console.log('订单类型:', order.type, '订单标题:', order.title)
    
    // 为不同类型的订单生成更具体的信息
    if (order.type === 'delivery') {
      // 外卖订单
      deliveryTime = order.timeSlot ? `今日 ${order.timeSlot.split('-')[1]}:00` : '30分钟内'
      if (order.title.includes('黄焖鸡米饭')) {
        itemName = '黄焖鸡米饭套餐'
      } else if (order.title.includes('麻辣烫')) {
        itemName = '麻辣烫(大份)'
      } else {
        itemName = order.title.replace('帮拿外卖【', '').replace('】', '')
      }
      console.log('外卖订单详情:', { itemName, deliveryTime })
    } else {
      // 快递订单
      deliveryTime = order.timeSlot ? `今日 ${order.timeSlot.split('-')[1]}:00前` : '今日18:00前'
      if (order.title.includes('宿舍楼A栋')) {
        itemName = '中(鞋盒大小)(零食)校重关'
      } else if (order.title.includes('图书馆')) {
        itemName = '文件资料包裹'
      } else if (order.title.includes('食堂')) {
        itemName = '日用品包裹(小件)'
      } else {
        itemName = '快递包裹(中等)'
      }
      console.log('快递订单详情:', { itemName, deliveryTime })
    }
    
    // 生成更详细的收件人地址
    let detailedAddress = deliveryAddress
    if (deliveryAddress.includes('宿舍楼A栋')) {
      detailedAddress = '宿舍楼A栋101室'
    } else if (deliveryAddress.includes('图书馆')) {
      detailedAddress = '图书馆阅览室'
    } else if (deliveryAddress.includes('教学楼')) {
      detailedAddress = '教学楼1号楼202室'
    } else if (deliveryAddress.includes('宿舍楼B栋')) {
      detailedAddress = '宿舍楼B栋305室'
    } else if (deliveryAddress.includes('食堂')) {
      detailedAddress = '食堂工作间'
    }
    
    console.log('地址详情:', { original: deliveryAddress, detailed: detailedAddress })
    
    // 转换数据格式
    orderDetail.value = {
      id: order.id,
      orderNumber: `2025${String(order.id).padStart(13, '*')}`,
      orderTime: order.time.replace('今日 ', ''),
      updateTime: new Date().toLocaleString().replace(/\//g, '-'),
      itemName: itemName,
      price: order.price + '.00',
      pickupLocation: pickupLocation,
      recipientName: recipients[randomIndex],
      recipientPhone: phones[randomIndex],
      deliveryAddress: detailedAddress,
      genderLimit: '不限',
      deliveryTime: deliveryTime,
      extraFee: '0',
      actualIncome: order.price + '.00',
      serviceType: order.type === 'delivery' ? 'takeout' : 'express',
      originalOrderData: order
    }
    
    console.log('最终生成的订单详情:', orderDetail.value)
  } else {
    console.log('未找到storage中的订单数据')
  }
}

// 方法
const goBack = () => {
  uni.navigateBack()
}

const contactCustomer = () => {
  uni.showModal({
    title: '联系客服',
    content: '是否要联系客服？',
    success: (res: any) => {
      if (res.confirm) {
        uni.showToast({
          title: '正在联系客服...',
          icon: 'none'
        })
      }
    }
  })
}

const grabOrder = async () => {
  if (isGrabbing.value) return
  
  uni.showModal({
    title: '确认抢单',
    content: `确定要抢这个订单吗？实际收入：${orderDetail.value.actualIncome}元`,
    success: async (res: any) => {
      if (res.confirm) {
        isGrabbing.value = true
        
        try {
          // 获取用户ID
          const userId = uni.getStorageSync('userId') || 'user_' + Date.now()
          if (!uni.getStorageSync('userId')) {
            uni.setStorageSync('userId', userId)
          }
          
          // 准备请求数据 - 统一数据格式
          const requestData = {
            orderId: String(orderDetail.value.id), // String类型，与数据库一致
            userId: String(userId), // String类型，必需
            title: String(orderDetail.value.itemName || '未知商品'), // String类型，必需
            pickup: String(orderDetail.value.pickupLocation || ''), // String类型，必需
            delivery: String(orderDetail.value.deliveryAddress || ''), // String类型，必需
            price: String(orderDetail.value.price || '0.00'), // String类型，必需
            serviceType: orderDetail.value.serviceType === 'takeout' ? 'takeout' : 'express', // 枚举值，必需
            originalOrder: orderDetail.value.originalOrderData || {
              timeSlot: orderDetail.value.deliveryTime,
              type: orderDetail.value.serviceType,
              orderNumber: orderDetail.value.orderNumber
            }
          }
          
          console.log('准备发送的请求数据:', requestData)
          console.log('请求URL:', `${requestUrl}/jjk/myOrders/add`)
          
          // 检查是否已经抢过这个订单
          const myOrders = uni.getStorageSync('myOrders') || '[]'
          const myOrdersList = JSON.parse(myOrders)
          const alreadyGrabbed = myOrdersList.find((order: any) => 
            order.id === Number(orderDetail.value.id) || order.orderId === String(orderDetail.value.id)
          )
          
          if (alreadyGrabbed) {
            uni.showToast({
              title: '您已经抢过这个订单了',
              icon: 'none'
            })
            isGrabbing.value = false
            return
          }
          
          // 调用后端API
          const response = await uni.request({
            url: `${requestUrl}/jjk/myOrders/add`,
            method: 'POST',
            data: requestData
          })
          
          console.log('服务器响应:', response)
          
          if (response.data.success) {
            // 同时保存到本地存储作为备用
            saveToLocalStorage()
            
            // 通知抢单大厅移除此订单
            uni.$emit('orderGrabbed', orderDetail.value.id)
            
            uni.showToast({
              title: '抢单成功！',
              icon: 'success'
            })
            
            // 延迟跳转到我的接单页面
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/JJK/my-orders'
              })
            }, 1500)
          } else {
            console.error('抢单失败:', response.data)
            uni.showToast({
              title: response.data.message || '抢单失败',
              icon: 'error'
            })
            saveToLocalStorage() // fallback
          }
        } catch (error) {
          console.error('抢单失败详情:', error)
          
          let errorMessage = '网络错误，已保存到本地'
          
          // 处理不同类型的错误
          if (error.statusCode === 400) {
            errorMessage = error.data?.message || '请求参数错误'
            console.error('400错误详情:', error.data)
          } else if (error.statusCode === 500) {
            errorMessage = '服务器繁忙，已保存到本地'
          } else if (error.statusCode === 404) {
            errorMessage = '接口不存在'
          } else {
            console.error('未知错误:', error)
          }
          
          uni.showToast({
            title: errorMessage,
            icon: 'none'
          })
          saveToLocalStorage() // fallback
        } finally {
          isGrabbing.value = false
        }
      }
    }
  })
}

// 本地存储备用方案 - 统一数据格式
const saveToLocalStorage = () => {
  const myOrders = uni.getStorageSync('myOrders') || '[]'
  const myOrdersList = JSON.parse(myOrders)
  
  // 与数据模型保持一致的格式
  const newMyOrder = {
    id: Number(orderDetail.value.id), // 前端显示用ID
    orderId: String(orderDetail.value.id), // 与数据库一致的字符串格式
    title: String(orderDetail.value.itemName || '未知商品'), // String类型
    pickup: String(orderDetail.value.pickupLocation || ''), // String类型
    delivery: String(orderDetail.value.deliveryAddress || ''), // String类型
    price: String(orderDetail.value.price || '0.00'), // String类型
    status: 'ongoing', // 枚举值
    serviceType: orderDetail.value.serviceType === 'takeout' ? 'takeout' : 'express', // 枚举值
    acceptTime: new Date().toLocaleString()
  }
  
  // 避免重复添加
  const exists = myOrdersList.find((order: any) => order.id === newMyOrder.id || order.orderId === newMyOrder.orderId)
  if (!exists) {
    myOrdersList.unshift(newMyOrder)
    uni.setStorageSync('myOrders', JSON.stringify(myOrdersList))
    console.log('订单已保存到本地存储:', newMyOrder)
  } else {
    console.log('订单已存在，跳过本地保存')
  }
}
</script>

<style lang="scss" scoped>
.grab-order-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100px;
}

.order-info-card {
  background-color: #fff;
  margin: 16px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      font-size: 15px;
      color: #666;
      font-weight: 500;
    }
    
    .value {
      font-size: 15px;
      color: #333;
      font-weight: 600;
    }
  }
}

.section-title {
  padding: 16px 20px 8px;
  
  text {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
}

.item-details-card {
  background-color: #fff;
  margin: 0 16px 16px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .section-subtitle {
    margin-bottom: 16px;
    
    text {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }
  
  .item-info {
    .item-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      .item-name {
        flex: 1;
        font-size: 15px;
        color: #333;
        font-weight: 500;
      }
      
      .item-price {
        font-size: 16px;
        color: #ff6b4a;
        font-weight: bold;
      }
    }
    
    .pickup-location {
      display: flex;
      align-items: center;
      
      .pickup-label {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
        min-width: 80px;
      }
      
      .pickup-value {
        flex: 1;
        font-size: 14px;
        color: #333;
      }
    }
  }
}

.recipient-card {
  background-color: #fff;
  margin: 0 16px 16px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .recipient-row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .recipient-label {
      font-size: 15px;
      color: #666;
      min-width: 80px;
      font-weight: 500;
    }
    
    .recipient-value {
      flex: 1;
      font-size: 15px;
      color: #333;
      font-weight: 600;
      
      &.phone {
        color: #ff6b4a;
      }
    }
    
    .phone-container {
      display: flex;
      align-items: center;
      flex: 1;
      
      .phone-icon {
        margin-right: 6px;
        font-size: 16px;
      }
    }
  }
}

.delivery-details-card {
  background-color: #fff;
  margin: 0 16px 16px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .detail-label {
      font-size: 15px;
      color: #666;
      font-weight: 500;
    }
    
    .detail-value {
      font-size: 15px;
      color: #333;
      font-weight: 600;
      
      &.income {
        color: #ff6b4a;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 16px 20px;
  display: flex;
  gap: 16px;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.1);
  
  .contact-btn {
    flex: 1;
    height: 48px;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 16px;
    color: #6c757d;
    
    .contact-icon {
      font-size: 18px;
    }
    
    .contact-text {
      font-weight: 500;
    }
  }
  
  .grab-btn {
    flex: 2;
    height: 48px;
    background-color: #ff6b4a;
    border: none;
    border-radius: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: bold;
    color: #fff;
    
    &:disabled {
      background-color: #ccc;
    }
  }
}
</style>
